<?php
/*
 * 我自己可能会用到的方法
 * @bzyy
 * 2015-7-4 11:50:49
 */



/*
 * 初始化redis
 *
 */
function init_redis()
{
    $redis = new RedisCluster();
    $redis->connect(array('host'=>'192.168.1.106','port'=>6379));
    $_ENV['redis'] = $redis;
    return $redis;
}

/*
 * ajax 数据返回
 */

function ajax_return($flag,$msg='',$data=array())
{
    echo json_encode(array('status'=>$flag,'message'=>$msg,'data'=>$data));
    die();
}


/*
 * 初始化mysql
 */
function init_mysql()
{
    $mysql = new class_mysql(MYSQL_HOST,MYSQL_USER,MYSQL_PWD,MYSQL_DB);
    $_ENV['mysql'] = $mysql;

    return $mysql;
}

/*
 * 取得一个商品数量的缓存
 *
 */
function get_goods_num($goods_id)
{
    $redis = $_ENV['redis'];
    //$num = $redis->set("goods_id:{$goods_id}",100);
    $num = $redis->get("goods_id:{$goods_id}");
    return intval($num);
}


/*
 * 取得商品信息
 */
function get_goods_info($goods_id)
{
    $redis = $_ENV['redis'];
    $goods_info = $redis->get("goods_info_{$goods_id}");
    if(!empty($goods_info))
    {
        $goods_info = json_decode($goods_info,true);
    }
    return $goods_info;

}

/*
 * 生成一个队列key
 */
function make_queue_key($goods_id,$session_id)
{
    return md5($goods_id."_goods_session_".$session_id);
}

/*
 * 把一个用户的请求加入到队列中，一遍后台处理
 *
 */
function insert_queue($goods_id,$queue_sn)
{
    $redis = $_ENV['redis'];
    $redis->lpush("queue_goods_{$goods_id}",$queue_sn);

    //设置一下数量
    $redis->incr("num_goods_{$goods_id}");
    $redis->set($queue_sn,time());
}


/*
 * 取得最大的队里数量
 *
 */
function max_queue_num($goods_num)
{
    return min($goods_num*5,QUEUE_MAX_NUM);
}

/*
 * 取得当前的队列数量
 */
function now_queue_num($goods_id)
{
    $redis = $_ENV['redis'];
    $num = $redis->get("num_goods_{$goods_id}");
    return max($num,0);
}





























